/*******************************************************************************
 * Copyright (c) 2000, 2005 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package edu.uts.reekie.designer.model.commands;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.gef.commands.Command;

import edu.uts.reekie.designer.Messages;
import edu.uts.reekie.designer.model.*;


/* TODO: generalize for view types */
public class DeleteCommand
	extends Command
{

private ViewNode child;
private AbstractDiagram parent;
private int index = -1;
private List<ViewElement> sourceConnections = new ArrayList<ViewElement>();
private List<ViewElement> targetConnections = new ArrayList<ViewElement>();

public DeleteCommand() {
	super(Messages.DeleteCommand_Label);
}

private void deleteConnections(ViewNode part) {
	if (part instanceof AbstractDiagram) {
		List<ViewNode> children = ((AbstractDiagram)part).getChildren();
		for (int i = 0; i < children.size(); i++)
			deleteConnections((ViewNode)children.get(i));
	}
	sourceConnections.addAll(part.getSourceConnections());
	for (int i = 0; i < sourceConnections.size(); i++) {
		AbstractConnector c = (AbstractConnector)sourceConnections.get(i);
		c.disconnect();
	}
	targetConnections.addAll(part.getTargetConnections());
	for (int i = 0; i < targetConnections.size(); i++) {
		AbstractConnector c = (AbstractConnector)targetConnections.get(i);
		c.disconnect();
	}
}


public void execute() {
	primExecute(); 
}

protected void primExecute() {
	deleteConnections(child);
	index = parent.getChildren().indexOf(child);
	parent.removeChild(child);
}


public void redo() {
	primExecute();
}

private void restoreConnections() {
	for (int i = 0; i < sourceConnections.size(); i++) {
		AbstractConnector c = (AbstractConnector)sourceConnections.get(i);
		c.reconnect();
	}
	sourceConnections.clear();
	for (int i = 0; i < targetConnections.size(); i++) {
		AbstractConnector c = (AbstractConnector)targetConnections.get(i);
		c.reconnect();
	}
	targetConnections.clear();
}

public void setChild (ViewNode c) {
	child = c;
}

public void setParent(AbstractDiagram p) {
	parent = p;
}

public void undo() {
	parent.addChild(child, index);
	restoreConnections();
}

}
